package com.jt.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private RemoteUserService remoteUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获得用户信息

        com.jt.pojo.User user = remoteUserService.selectUserByUsername(username);
        if(user == null){
            throw  new UsernameNotFoundException("用户不存在");
        }

        //查询权限
        List<String> permissions = remoteUserService.selectUserPermissions(user.getId());
        log.info("permissions {}",permissions);

        User userInfo = new User(username,user.getPassword(),
                AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{})));

        //返回给认证中心,认证中心会基于用户输入的密码和数据库密码进行比较
        return userInfo;
    }
}
